import { defineStore } from "pinia";
import { ref } from "vue";

export const userStore = defineStore('user', () => {
    // state
    const state = ref({
        token: localStorage.getItem('token') || '',
        role: localStorage.getItem('role') || '',
        userInfo: {}
    })
    
    // action
    const setRole = (type: string) => {
        state.value.role = type
    }
    const setUserInfo = (data: any) => {
        state.value.userInfo = data.user_info
        state.value.token = data.token
        state.value.role = data.user_info.role || '1'
        // 存储token在localStorage
        localStorage.setItem('token', state.value.token)
        // 存储权限在localStorage
        localStorage.setItem('role', state.value.role)
    }
    // 退出登录 
    const logout = () => {
        // 清空 token 和 userInfo
        state.value.token = ''
        state.value.userInfo = {}
        // 清空localStorage的 token 和 role
        localStorage.removeItem('token')
        localStorage.removeItem('role')
    }

    return {
        state,
        setRole,
        setUserInfo,
        logout
    }
})